﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Net;

namespace Common.Tools.Filter
{
    /// <summary>
    /// 全局异常过滤器
    /// </summary>
    public class ExceptionFilter : ExceptionFilterAttribute
    {
        private readonly ILogger<ExceptionFilter> _logger;
        /// <summary>
        /// 构造函数注入
        /// </summary>
        /// <param name="logger"></param>
        public ExceptionFilter(ILogger<ExceptionFilter> logger)
        {
            _logger = logger;
        }
        /// <summary>
        /// 全局捕获异常方法
        /// </summary>
        /// <param name="context"></param>
        public override void OnException(ExceptionContext context)
        {
            //如果异常没有被处理则进行处理
            if (!context.ExceptionHandled)
            {
                var ex = context.Exception;
                var errMsg = "全局检测到未捕获异常：" + ex.Message;
                _logger.LogError(ex, errMsg);
                LogHelper.Error($"全局检测到未捕获异常：{ex.Message},ex{JsonConvert.SerializeObject(ex)}");
                // 定义返回类型
                var result = new
                {
                    Code = 500,
                    Message = context.Exception.Message,
                };
                context.Result = new ContentResult
                {
                    // 返回状态码设置为500，表示内部错误
                    StatusCode = (int)HttpStatusCode.InternalServerError,
                    // 设置返回格式
                    ContentType = "application/json;charset=utf-8",
                    Content = JsonConvert.SerializeObject(result)
                };
            }
            // 设置为true，表示异常已经被处理了
            context.ExceptionHandled = true;
            return;
        }
    }

}
